﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WuxiWTO.Mapping;
using WutiWTO.Common;

namespace WuxiWTO.Web
{
    public partial class articledetails : System.Web.UI.Page
    {
        private string pid = "";
        private string cid = "";

        public string article_title = "";
        public string author = "";
        public string source = "";
        public string writer = "";
        public string created_date = "";
        public string read_count = "";


        protected bool SinglePage
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["s"]))
                {
                    pid = Request.QueryString["pid"];
                    cid = Request.QueryString["cid"];
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        private void SetExtendParame()
        {
            int currentID = 0;
            if (SinglePage)
            {
                ViewState["pid"] = pid;
                ViewState["cid"] = cid;

                int intPid = 0;
                int.TryParse(pid, out intPid);
                int intCid = -1;
                if (!string.IsNullOrEmpty(cid))
                {
                    intCid = int.Parse(cid);
                }
                article art = ctx.articles.OrderByDescending(p=>p.created_date).SingleOrDefault(p => p.parent_category_id == intPid && p.category_id == intCid);
                if (art != null)
                {
                    currentID = art.article_id;
                    article_title = art.article_title;
                    author = art.author;
                    source = art.source;
                    writer = art.created_user;
                    created_date = art.created_date.Value.ToShortDateString();
                    read_count = art.read_count.ToString();
                    litContent.Text = art.article_content;
                    if (!string.IsNullOrEmpty(art.attachment_path))
                    {
                        ViewState["file_path"] = art.attachment_path;
                        btnDownloadFile.Visible = true;
                        this.btnDownloadFile.Text = art.attachment_path.Substring(art.attachment_path.LastIndexOf("/") + 1, art.attachment_path.Length - art.attachment_path.LastIndexOf("/") - 1);
                    }
                    else
                    {
                        btnDownloadFile.Visible = false;
                    }

                    art.read_count = art.read_count + 1;
                    ctx.SubmitChanges();
                }
                else
                {
                    category cat;
                    if (intCid != 0 && intCid != -1)
                    {
                        cat = ctx.categories.SingleOrDefault(p => p.art_kind_id == intCid);
                    }
                    else
                    {
                        cat = ctx.categories.SingleOrDefault(p => p.art_kind_id == intPid);
                    }
                    if (cat != null)
                    {
                        article_title = cat.art_kind_name;
                    }
                }
                //获取上一篇下一篇
                GetPrevAndNextArticle(currentID);
                return;
            }
            else
            {
                string articleID = Request.QueryString["aid"];
                if (!string.IsNullOrEmpty(articleID))
                {
                    int aid = int.Parse(articleID);
                    article art = ctx.articles.SingleOrDefault(p => p.article_id == aid);
                    ViewState["pid"] = art.parent_category_id;
                    ViewState["cid"] = art.category_id;
                    currentID = art.article_id;
                    article_title = art.article_title;
                    author = art.author;
                    source = art.source;
                    writer = art.created_user;
                    read_count = art.read_count.ToString();
                    created_date = art.created_date.Value.ToShortDateString();
                    litContent.Text = art.article_content;
                    if (!string.IsNullOrEmpty(art.attachment_path))
                    {
                        ViewState["file_path"] = art.attachment_path;
                        btnDownloadFile.Visible = true;
                        this.btnDownloadFile.Text = art.attachment_path.Substring(art.attachment_path.LastIndexOf("/") + 1, art.attachment_path.Length - art.attachment_path.LastIndexOf("/") - 1);
                    }
                    else
                    {
                        btnDownloadFile.Visible = false;
                    }
                    //获取上一篇下一篇
                    GetPrevAndNextArticle(currentID);
                    art.read_count = art.read_count + 1;
                    ctx.SubmitChanges();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "paraerr", "alert('参数传递错误');location='default.aspx';", true);
                }
                return;
            }
            

        }

        private void GetExtraParame()
        {
            pid = ViewState["pid"] == null ? "" : ViewState["pid"].ToString();
            cid = ViewState["cid"] == null ? "" : ViewState["cid"].ToString();
        }

        WTODataContext ctx = new WTODataContext();

        protected void Page_Load(object sender, EventArgs e)
        {
            //该页面分为单一页面（从文章列表页面直接传递而来，s=y.还有一种正常路径传递而来。所以要分为两种不同的情况）
            if (!IsPostBack)
            {
                SetExtendParame();
                GetExtraParame();
                BuildParentCategoryList();
            }
        }

        private void GetPrevAndNextArticle(int currentID)
        {
            usp_get_prev_articleResult prev = CategoryInfo.GetPrevArticle(currentID);
            usp_get_next_articleResult next = CategoryInfo.GetNextArticle(currentID);
            if (prev != null)
            {
                this.hyPrev.Text = string.Format("上一篇：<a title='{1}' href='articleDetails.aspx?aid={0}'>{2}</a>", prev.article_id, prev.article_title, Utility.CutStringByLength(prev.article_title, 20));
            }
            else
            {
                this.hyPrev.Text = "上一篇：已经没有了";
            }

            if (next != null)
            {
                this.hyNext.Text = string.Format("下一篇：<a title='{1}' href='articleDetails.aspx?aid={0}'>{2}</a>", next.article_id, next.article_title, Utility.CutStringByLength(next.article_title, 20));
            }
            else
            {
                this.hyNext.Text = "下一篇：已经没有了";
            }
        }

        protected void btnDownloadFile_Click(object sender, EventArgs e)
        {
            if (ViewState["file_path"] != null)
            {
                string fileName = ViewState["file_path"].ToString();//客户端保存的文件名
                fileName = fileName.Substring(fileName.LastIndexOf("/") + 1, fileName.Length - fileName.LastIndexOf("/") - 1);
                string filePath = Server.MapPath("~/") + ViewState["file_path"].ToString();//路径

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
                if (fileInfo.Exists)
                {
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    Response.AddHeader("Content-Transfer-Encoding", "binary");
                    Response.ContentType = "application/octet-stream";
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    Response.WriteFile(fileInfo.FullName);
                    Response.Flush();
                    Response.End();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "fa", "alert('该文件不存在');", true);
                    return;
                }
            }

        }


        #region 构筑左边的二级菜单以及导航面包屑
        private void BuildParentCategoryList()
        {
            string strParentCategory = "";

            if (!string.IsNullOrEmpty(pid))
            {
                int intPid = int.Parse(pid);
                //导航栏项目
                var parent = ctx.categories.SingleOrDefault(p => p.art_kind_id == intPid);
                if (parent != null)
                {
                    //URL不为空的话，点击就进入设置好的URL页面
                    if (!string.IsNullOrEmpty(parent.url))
                    {
                        litBreakCrumbs.Text = string.Format("<a href=\"{0}\">{1}</a>", parent.url, parent.alias == "" ? parent.art_kind_name : parent.alias);
                    }
                    else
                    {
                        litBreakCrumbs.Text = string.Format("<a href=\"articleList.aspx?pid={0}\">{1}</a>", parent.art_kind_id, parent.alias == "" ? parent.art_kind_name : parent.alias);
                    }
                }
                //如果子级类别不为空。则继续构筑导航
                if (!string.IsNullOrEmpty(cid))
                {
                    int intCid = int.Parse(cid);
                    var child = ctx.categories.SingleOrDefault(p => p.art_kind_id == intCid);
                    if (child != null)
                    {
                        if (!string.IsNullOrEmpty(child.url))
                        {
                            litBreakCrumbs.Text += string.Format("<span>&gt;&gt;</span><a href=\"{0}\">{1}</a>", child.url, child.alias == "" ? child.art_kind_name : child.alias);
                        }
                        else
                        {
                            litBreakCrumbs.Text += string.Format("<span>&gt;&gt;</span><a href=\"articleList.aspx?pid={0}&cid={1}\">{2}</a>", child.art_parent_kind, child.art_kind_id, child.alias == "" ? child.art_kind_name : child.alias);
                        }
                    }
                }
                //构建左边的二级菜单
                var list = ctx.categories.OrderBy(p=>p.sort_num).Where(p => p.art_parent_kind == intPid).ToList();
                foreach (category cat in list)
                {
                    if (!string.IsNullOrEmpty(cat.url))
                    {
                        strParentCategory += string.Format("<li><a href='{0}'>{1}</a></li>", cat.url, cat.art_kind_name);
                    }
                    else
                    {
                        strParentCategory += string.Format("<li><a href='articleList.aspx?pid={0}&cid={1}'>{2}</a></li>", cat.art_parent_kind, cat.art_kind_id, cat.art_kind_name);
                    }
                }
                //如果为空，表示点击的一级分类下面没有二级分类
                if (string.IsNullOrEmpty(strParentCategory))
                {
                    if (!string.IsNullOrEmpty(parent.url))
                    {
                        strParentCategory = string.Format("<li><a href='{0}'>{1}</a></li>", parent.url, parent.alias == "" ? parent.art_kind_name : parent.alias);
                    }
                    else
                    {
                        strParentCategory = string.Format("<li><a href='articleList.aspx?pid={0}'>{1}</a></li>", parent.art_kind_id, parent.alias == "" ? parent.art_kind_name : parent.alias);
                    }
                }
                this.litParentCategoryName.Text = parent.alias == "" ? parent.art_kind_name : parent.alias;
                this.litParentCategoryList.Text = strParentCategory;
            }
        }
        #endregion

    }
}